﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using InhollandAir.App_Code;


namespace InhollandAir
{
    public partial class ForgotUsername : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btn_AskUsername_Click(object sender, EventArgs e)
        {
            string email = txt_Email.Text;
            Tools.WaitAFewSeconds(1);
            Page.Validate();
            if (!Page.IsValid)
            {
                lbl_Info.Text = "Something went wrong, please try again.";
                lbl_Info.Visible = true;
                return;
            }
            if (!string.IsNullOrEmpty(email))
            {
                var conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ReadUser"].ToString());
                if (conn.State == ConnectionState.Closed) conn.Open();
                try
                {
                    SqlCommand cmd = new SqlCommand("select * from account where email=@Email", conn);
                    cmd.Parameters.AddWithValue("@Email", email);
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.HasRows)
                    {
                        lbl_Info.Text = "E-mail has been sent to" + Server.HtmlEncode(email) + ".";
                        lbl_Info.Visible = true;
                    }
                    else
                    {
                        lbl_Info.Text = "E-mail address is not known to us.";
                        lbl_Info.Visible = true;
                        lbl_Info.CssClass = "alert alert-info";
                    }
                }
                catch (SqlException exception)
                {
                    Logging.WriteError(exception.Message);
                    lbl_Error.Text = "Database unavailable, please try again later.";
                }
                catch (Exception exception)
                {
                    Logging.WriteError(exception.Message);
                    lbl_Error.Text = "Failed to send username, please contact the admin.";
                }
                finally
                {
                    conn.Close();
                }
            }
        }
    }
}